

from django.core.management.base import BaseCommand

from django.contrib.auth.hashers import make_password

from django.contrib.auth.models import Group

from django.conf import settings

from z_import.models import MyUser, ClinicalProjects

from z_import.cons import current_area, current_info
from z_import.cons import start_row, end_row, prj_code


class Command(BaseCommand):

    help = 'Add users to clinicalV3'

    def add_arguments(self, parser):
        parser.add_argument('-f',
                            '--file_path',
                            required=True,
                            help='文件路径(绝对路径)')
        parser.add_argument('-g',
                            '--group_name',
                            required=True,
                            help='组名')
        parser.add_argument('-s',
                            '--start_row',
                            default=start_row,
                            required=False, help='起始行')
        parser.add_argument('-e',
                            '--end_row',
                            default=end_row,
                            required=False, help='终止行')
        parser.add_argument('-p',
                            '--prj_code',
                            default=prj_code,
                            required=False,
                            help='项目的linkurl(例如: project001/); 默认 project001/')

    def analyse(self,
                sheet_one,
                area_col,
                user_name_col,
                sex_col,
                hospital_col,
                # address_col,
                phone_col,
                email_col,
                prj_code,
                cur_row,
                end_row,
                group_obj):
        area = sheet_one['{}{}'.format(area_col, cur_row)].value
        user_name = sheet_one['{}{}'.format(user_name_col, cur_row)].value
        sex = sheet_one['{}{}'.format(sex_col, cur_row)].value
        hospital = sheet_one['{}{}'.format(hospital_col, cur_row)].value
        # address = sheet_one['{}{}'.format(address_col, cur_row)].value
        phone = sheet_one['{}{}'.format(phone_col, cur_row)].value
        email = sheet_one['{}{}'.format(email_col, cur_row)].value

        try:
            prj = ClinicalProjects.objects.get(prj_code=prj_code)
        except ClinicalProjects.DoesNotExist:
            return 'error: 项目代码错误'

        if area:
            current_area.clear()
            current_area.append(area)

        try:
            len_of_phone = len(phone)
        except Exception:
            len_of_phone = 0

        if len_of_phone > 11:
            phone = str(phone).strip()

            phone_list = phone.split(r'/')

            phone = phone_list[0].strip()

        current_info['area'] = current_area[0]
        current_info['user_name'] = user_name
        current_info['sex'] = sex
        current_info['hospital'] = hospital
        # current_info['address'] = address
        current_info['phone'] = phone
        current_info['email'] = email

        user_is_existed = None

        if not current_info.get('address'):
            current_info['address'] = '未填写'

        if not current_info.get('sex'):
            current_info['sex'] = '未知'

        try:
            if current_info.get('phone'):
                user_is_existed = MyUser.objects.filter(phone=current_info.get('phone'))
            if current_info.get('email') and not user_is_existed:
                user_is_existed = MyUser.objects.filter(email=current_info.get('email'))
        except Exception as e:
            return 'error: %s' % e

        if current_info.get('email') or current_info.get('phone'):
            if not current_info.get('email') and current_info.get('phone'):
                current_info['email'] = '%s@example.com' % current_info.get('phone')

            if not current_info.get('phone') and current_info.get('email'):
                current_info['phone'] = '00000000000'

            # 检查用户不存在 => 保存; 存在 => 继续
            if not user_is_existed:
                try:
                    current_info_strip = {}
                    for k, v in current_info.items():
                        if isinstance(v, str):
                            current_info_strip[k] = v.strip()
                        else:
                            current_info_strip[k] = v
                    user = MyUser(**current_info_strip)
                    user.password = make_password(settings.BEGIN_PASS)
                except Exception as e:
                    return 'error: %s' % e
                else:
                    try:
                        user.save()
                        # 添加权限
                        user.groups.add(group_obj)
                        # 添加项目
                        prj.relusers.add(user)
                        prj.save()
                    except Exception as e:
                        return 'error: %s' % e
                    else:
                        return 'success: 第%d行入库成功' % (cur_row)
            else:
                if user_is_existed[0] in group_obj.user_set.all():
                    return 'warning: 用户已存在'
                else:
                    user_is_existed[0].groups.add(group_obj)
                    return 'success: 用户分组成功'
        else:
            return 'success: 第%d行数据可忽略' % (cur_row)

    def handle(self, *args, **options):

        filename = options.get('file_path')
        group = options.get('group_name')
        prj_code = options.get('prj_code')
        start_row = int(options.get('start_row'))
        end_row = int(options.get('end_row'))
        area_col = 'A'
        user_name_col = 'B'
        sex_col = 'C'
        hospital_col = 'D'
        # address_col = 'E'
        phone_col = 'E'
        email_col = 'F'

        group_name_of_list = Group.objects.values('name')

        name_list = [group_name.get('name') for group_name in list(group_name_of_list)]

        if group not in name_list:
            self.stderr.write('分组不存在, 查看组别名称是否输入正确')
            return

        try:
            group_obj = Group.objects.get(name=group)
        except Group.DoesNotexist:
            self.stderr.write('分组不存在, 查看组别名称是否输入正确')
            return

        import openpyxl

        wb = openpyxl.load_workbook(filename)

        sheetsname = wb.sheetnames

        # 只有一个表格的情况下
        sheet_one = wb[sheetsname[0]]

        for cur_row in range(start_row, end_row + 1):

            is_saved = self.analyse(sheet_one,
                                    area_col,
                                    user_name_col,
                                    sex_col,
                                    hospital_col,
                                    # address_col,
                                    phone_col,
                                    email_col,
                                    prj_code,
                                    cur_row,
                                    end_row,
                                    group_obj)

            if 'error' in is_saved:
                self.stderr.write('第%s行%s' % (cur_row, is_saved))
            if 'warning' in is_saved:
                self.stdout.write('第%s行%s' % (cur_row, is_saved))
            if 'success' in is_saved:
                self.stdout.write(self.style.SUCCESS(is_saved))
